package com.wan.activity;

import java.util.HashMap;
import net.sourceforge.simcpux.Util;

import com.reyun.sdk.ReYunTrack;
import com.wan.activity.util.EditTextFocusLintener;
import com.wan.commonsdk.Conet;
import com.wan.commonsdk.HttpUtils;
import com.wan.commonsdk.WanCommonSdk;
import com.wan.commonsdk.WanServerResposeCode;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
//------------------------------------------------------------------------
//
// 用户登录
//
//------------------------------------------------------------------------

public class LoginActivity extends BaseActivity implements OnClickListener {
	private final int LOGIN_SUCCESS = WanServerResposeCode.WAN_LOGIN_SUCCESS;
	private final int LOGIN_FAILURE = WanServerResposeCode.WAN_LOGIN_FAILURE;
	private final int NETWORK_ERROR = 10086;
	private Button btn_login, btn_regester, btn_forgetpassword;
	private EditText et_username, et_password;
	private TextView login_back_btn;
	private Thread mThread;
	private String username, password, guestname, status;
	private boolean GuestLogin = false;
	Dialog dialog;
	private RelativeLayout wan51_phone_reg, btn_guestlogin;

	private Button login_un_edclose, login_pw_edclose;

	private CheckBox auto_save;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (WanCommonSdk.screen_orientation == WanCommonSdk.SCREEN_ORIENTATION_PORTRAIT) {
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		} else {
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		super.onCreate(savedInstanceState);
		setContentView(Util.getResID("wan51_login", "layout"));
		Conet conet = Conet.getInstance();
		conet.addActivity(this);
		String username = "", password = "";

		Intent intent = getIntent();

		username = intent.getStringExtra("username");
		password = intent.getStringExtra("password");
		this.btn_login = (Button) findViewById(Util.getResID("btn_login", "id"));

		btn_login.setOnClickListener(this);
		this.btn_regester = (Button) findViewById(Util.getResID("btn_regester",
				"id"));

		btn_regester.setOnClickListener(this);
		this.btn_guestlogin = (RelativeLayout) findViewById(Util.getResID(
				"btn_enter", "id"));

		btn_guestlogin.setOnClickListener(this);
		/*
		 * login_back_btn = (TextView) findViewById(Util.getResID(
		 * "login_back_btn", "id"));
		 * 
		 * login_back_btn.setOnClickListener(this);
		 */
		this.btn_forgetpassword = (Button) findViewById(Util.getResID(
				"btn_forgetpassword", "id"));

		btn_forgetpassword.setOnClickListener(this);

		wan51_phone_reg = (RelativeLayout) findViewById(Util.getResID(
				"wan51_phone_reg", "id"));
		wan51_phone_reg.setOnClickListener(this);

		this.et_username = (EditText) findViewById(Util.getResID("et_username",
				"id"));

		this.et_password = (EditText) findViewById(Util.getResID("et_password",
				"id"));

		if (username != null && username.length() > 0) {
			et_username.setText(username);
		}
		if (password != null && password.length() > 0 && !"0".equals(password) && Conet.isJZPW == 0) {
			et_password.setText(password);
		}

		login_un_edclose = (Button) findViewById(Util.getResID(
				"login_un_edclose", "id"));
		et_username.setOnFocusChangeListener(new EditTextFocusLintener(
				et_username, login_un_edclose));

		login_pw_edclose = (Button) findViewById(Util.getResID(
				"login_pw_edclose", "id"));
		et_password.setOnFocusChangeListener(new EditTextFocusLintener(
				et_password, login_pw_edclose));
		auto_save = (CheckBox) findViewById(Util.getResID("auto_save", "id"));
		auto_save.setOnClickListener(this);
	}

	// ------------------------------------------------------------------------
	//
	// 消息处理
	//
	// ------------------------------------------------------------------------
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {// �˷�����ui�߳�����
			switch (msg.what) {

			case LOGIN_SUCCESS:
				hideLoading();
				// Toast.makeText(getApplication(), "�ɹ�",
				// Toast.LENGTH_LONG).show();
				// Util.LogUtil("mhandler------------");
				// Conet.mUserInfo = (UserInfo) msg.obj;
				// if (GuestLogin) {
				// LoginOperation.guestloginplatform(activity, guestname,
				// password, Conet.mUserInfo, LOGIN_SUCCESS,
				// WanCommonSdk.GUEST);
				// } else {
				// Log.d("LOG", "login----------");
				// LoginOperation.loginplatform(activity, username, password,
				// Conet.mUserInfo, LOGIN_SUCCESS,
				// WanCommonSdk.NORMAL_USER);
				// }
				if (!"0".equals(Conet.mUserInfo.getUser_password())) {
				}
				/*TalkingDataAppCpa.onRegister(Conet.mUserInfo.getUser_id());
				TalkingDataAppCpa.onLogin(Conet.mUserInfo.getUser_id());*/
				
				/*
				TrackingIO.setRegisterWithAccountID(Conet.mUserInfo.getUser_id());				
				TrackingIO.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());*/
				ReYunTrack.setRegisterWithAccountID(Conet.mUserInfo.getUser_id());
				ReYunTrack.setLoginSuccessBusiness(Conet.mUserInfo.getUser_id());
				// finish();
				WanCommonSdk.loginCallBack.loginSuccess(
						Conet.mUserInfo.getUser_id(),
						Conet.mUserInfo.getAccess_token());
				finish();
				// 返回登陆成功 函数
				break;
			case LOGIN_FAILURE:
				hideLoading();
				showHint(getString(Util.getResID("login_error_hint", "string")));
				mThread = null;
				break;
			case WanServerResposeCode.WAN_LOGIN_WRONG_USERNAME:
				hideLoading();
				showHint(getString(Util.getResID("login_username_hint",
						"string")));

				mThread = null;
				break;
			case WanServerResposeCode.WAN_LOGIN_WRONG_PASSWORD:
				hideLoading();
				showHint(getString(Util.getResID("login_password_hint",
						"string")));

				mThread = null;
				break;
			case NETWORK_ERROR:
				hideLoading();
				showHint(getString(Util.getResID("newwork_error", "string")));

				mThread = null;
				break;
			default:
				hideLoading();
				showToast(status);
				mThread = null;
				break;
			}
		}
	};

	// ------------------------------------------------------------------------
	//
	// 线程处理
	//
	// ------------------------------------------------------------------------
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			HashMap<String, String> result = null;
			Util.LogUtil("runnable------------");
			if (GuestLogin) {
				String jsonStr = Conet.WANSP.getString(Conet.SPUSER, "");
				Conet.mUserInfo.setGuest(true);
				// if (!jsonStr.equals("")) {
				// // 游客多次登录
				// try {
				// JSONObject jsonObject = new JSONObject(jsonStr);
				// guestname = jsonObject.getString("user_name");
				// if (guestname != null)
				// result = HttpUtils.HttpLogin(guestname, guestname);
				// Conet.mUserInfo.setUser_name(guestname);
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				// } else {
				result = HttpUtils.HttpGuestLogin();
				Log.e("result", result + "--------------");
				if (result != null
						&& result.get("status").equals(
								String.valueOf(LOGIN_SUCCESS))) {
					Conet.mUserInfo.setUser_id(result.get("user_id"));
					Conet.mUserInfo.setAccess_token(result.get("access_token"));
					Conet.mUserInfo.setUser_name(result.get("username"));
					Conet.mUserInfo.setUser_password("0");

					int isguest = HttpUtils.isGuest(result.get("userid"),
							result.get("username"));

					Log.e("isguest", isguest + "--------------");
					if (isguest == 2) {
						Conet.mUserInfo.setGuest(false);
					}
					mHandler.obtainMessage(LOGIN_SUCCESS, Conet.mUserInfo)
							.sendToTarget();
				}
				// }
			} else {

				result = HttpUtils.HttpLogin(username, password);
				Conet.mUserInfo.setUser_name(username);
				Conet.mUserInfo.setUser_password(password);
				Conet.mUserInfo.setGuest(false);
			}
			if (result == null) {
				mHandler.obtainMessage(NETWORK_ERROR).sendToTarget();
			} else {
				if (result.get("status").equals(String.valueOf(LOGIN_SUCCESS))) {
					Conet.mUserInfo.setUser_id(result.get("user_id"));
					Conet.mUserInfo.setAccess_token(result.get("access_token"));
					mHandler.obtainMessage(LOGIN_SUCCESS, Conet.mUserInfo)
							.sendToTarget();
				} else {
					mHandler.obtainMessage(LOGIN_FAILURE, Conet.mUserInfo)
							.sendToTarget();
				}
			}

		}
	};

	// ------------------------------------------------------------------------
	//
	// 事件处理
	//
	// ------------------------------------------------------------------------
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == Util.getResID("btn_login", "id")) {

			if (!checkUserInfo())
				return;
			username = this.et_username.getText().toString();
			password = this.et_password.getText().toString();
			GuestLogin = false;
			showLoading(this.getString(Util.getResID("log_loading_hint",
					"string")));

			mThread = new Thread(runnable);
			mThread.start();

		} else if (v.getId() == Util.getResID("btn_regester", "id")) {

			Intent intent = new Intent(this, RegesterActivity.class);
			this.startActivity(intent);
		} else if (v.getId() == Util.getResID("btn_enter", "id")) {

			username = "";
			password = "";
			GuestLogin = true;
			showLoading(this.getString(Util.getResID("glog_loading_hint",
					"string")));

			mThread = new Thread(runnable);
			mThread.start();

			// this.finish();
		} else if (v.getId() == Util.getResID("btn_forgetpassword", "id")) {

			Intent intent = new Intent(this, forgetPasswordActivity.class);
			this.startActivity(intent);
			// this.finish();
		} else if (v.getId() == Util.getResID("wan51_phone_reg", "id")) {
			Intent intent = new Intent(LoginActivity.this,
					WanPhoneRegesterActivity.class);
			startActivity(intent);
		} else if (v.getId() == Util.getResID("auto_save", "id")) {
			if (auto_save.isChecked()) {
				auto_save.setChecked(true);
			} else {
				auto_save.setChecked(false);
			}
		}
	}

	private Boolean checkUserInfo() {
		int un_length = this.et_username.getText().toString().length();
		int pw_length = this.et_password.getText().toString().length();

		if (un_length == 0) {
			showHint(this.getString(Util.getResID("username_empty_hint",
					"string")));
			return false;
		}
		if (pw_length == 0) {
			showHint(this.getString(Util.getResID("password_empty_hint",
					"string")));
			return false;
		}
		if (un_length < WanCommonSdk.MIN_USERNAME_LENGTH
				|| un_length > WanCommonSdk.MAX_USERNAME_LENGTH) {
			showHint(this.getString(Util.getResID("username_length_hint",
					"string")));
			return false;
		}
		if (pw_length < WanCommonSdk.MIN_PASSWORD_LENGTH
				|| pw_length > WanCommonSdk.MAX_PASSWORD_LENGTH) {
			showHint(this.getString(Util.getResID("password_length_hint",
					"string")));

			return false;
		}
		return true;
	}

	private void isbind_dialog() {
		dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCancelable(false);// 设置点击屏幕Dialog不消失
		dialog.setContentView(Util.getResID("xy_51wan_quit_dialog", "layout"));

		dialog.findViewById(Util.getResID("quit_dialog_btn", "id"))
				.setOnClickListener(this);

		dialog.findViewById(Util.getResID("canle_dialog_btn", "id"))
				.setOnClickListener(this);
		dialog.show();
	}
	@Override
	protected void onPause() {
		if(auto_save.isChecked()){
			Conet.isJZPW = 0;
		}else{
			Conet.isJZPW = 1;
		}
		super.onPause();
	}
}
